<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="案例标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入案例标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
             <el-form-item label="案例类型" prop="type">
         <el-select v-model="queryParams.type" placeholder="请选择案例类型" clearable>
           <el-option
             v-for="dict in dict.type.case_type"
             :key="dict.value"
             :label="dict.label"
             :value="dict.value"
           />
         </el-select>
       </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="caseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>

      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
             <el-table-column label="案例标题" align="center" prop="title" :show-overflow-tooltip="true"/>
       <el-table-column label="案例简介" align="center" prop="summary" :show-overflow-tooltip="true"/>
              <el-table-column label="案例类型" align="center" prop="type">
         <template slot-scope="scope">
           <dict-tag :options="dict.type.case_type" :value="scope.row.type"/>
         </template>
       </el-table-column>
      <el-table-column label="案例描述" align="center" prop="description" :show-overflow-tooltip="true"/>
             <el-table-column label="指标数量" align="center" prop="indicatorCount">
         <template slot-scope="scope">
           <span>{{ scope.row.indicator ? scope.row.indicator.length : 0 }}个</span>
         </template>
       </el-table-column>
      <el-table-column label="排序号" align="center" prop="sortNum"/>
      <el-table-column label="是否显示" align="center" prop="isShow">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.yes_or_no" :value="scope.row.isShow"/>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180"/>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >编辑
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改案例对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="案例标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入案例标题" />
            </el-form-item>
          </el-col>
                     <el-col :span="12">
             <el-form-item label="案例类型" prop="type">
               <el-select v-model="form.type" placeholder="请选择案例类型">
                 <el-option
                   v-for="dict in dict.type.case_type"
                   :key="dict.value"
                   :label="dict.label"
                   :value="dict.value"
                 />
               </el-select>
             </el-form-item>
           </el-col>
        </el-row>

                 <el-row :gutter="24">
           <el-col :span="12">
             <el-form-item label="排序号" prop="sortNum">
               <el-input-number v-model="form.sortNum" :min="0" :max="99999999" controls-position="right" placeholder="越大越靠前" />
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="是否显示" prop="isShow">
               <el-radio-group v-model="form.isShow">
                 <el-radio :label="1">显示</el-radio>
                 <el-radio :label="0">隐藏</el-radio>
               </el-radio-group>
             </el-form-item>
           </el-col>
         </el-row>

         <el-row :gutter="24">
           <el-col :span="24">
             <el-form-item label="案例简介" prop="summary">
               <el-input type="textarea" :rows="3" v-model="form.summary" placeholder="请输入案例简介" />
             </el-form-item>
           </el-col>
         </el-row>

                 <el-row :gutter="24">
           <el-col :span="24">
             <el-form-item label="案例描述" prop="description">
               <mavon-editor
                 v-model="form.description"
                 ref="md"
                 @imgAdd="$imgAdd"
                 @change="change"
                 style="min-height: 600px"
               />
             </el-form-item>
           </el-col>
         </el-row>

                   <!-- 指标数据管理 -->
          <el-row :gutter="24">
            <el-col :span="24">
                             <el-form-item label="指标数据" prop="indicator">
                 <div class="metrics-container">
                   <div class="metrics-header">
                     <span class="metrics-title">性能指标</span>
                     <el-button type="primary" size="mini" icon="el-icon-plus" @click="addIndicator">添加指标</el-button>
                   </div>

                   <div v-if="form.indicator && form.indicator.length > 0" class="metrics-list">
                     <div v-for="(indicator, index) in form.indicator" :key="index" class="metric-item">
                       <el-row :gutter="16">
                         <el-col :xs="24" :sm="8">
                           <el-form-item :label="'指标值'" :prop="'indicator.' + index + '.value'" :rules="{ required: true, message: '指标值不能为空', trigger: 'blur' }">
                             <el-input v-model="indicator.value" placeholder="如：3.5倍" />
                           </el-form-item>
                         </el-col>
                         <el-col :xs="24" :sm="12">
                           <el-form-item :label="'指标描述'" :prop="'indicator.' + index + '.label'" :rules="{ required: true, message: '指标描述不能为空', trigger: 'blur' }">
                             <el-input v-model="indicator.label" placeholder="如：计算性能提升" />
                           </el-form-item>
                         </el-col>
                                                  <el-col :xs="24" :sm="4">
                            <el-form-item label="操作">
                              <el-button
                                type="danger"
                                size="mini"
                                icon="el-icon-delete"
                                @click="removeIndicator(index)"
                                :disabled="form.indicator.length <= 1"
                              >删除</el-button>
                            </el-form-item>
                          </el-col>
                       </el-row>
                     </div>
                   </div>

                   <div v-else class="metrics-empty">
                     <el-empty description="暂无指标数据，请点击添加指标"></el-empty>
                   </div>
                 </div>
               </el-form-item>
            </el-col>
          </el-row>

                 <!-- 图片上传 -->
         <el-row :gutter="24">
           <el-col :span="24">
                           <el-form-item label="案例图片" prop="imageFileId">
                                <el-upload
                   :action="uploadAction"
                   list-type="picture-card"
                   :limit="1"
                   :file-list="imageFileList"
                   :headers="uploadHeaders"
                   :on-success="onImageUploadSuccess"
                   :on-remove="onImageUploadRemove"
                   :on-error="onImageUploadError"
                   :before-upload="onBeforeUpload"
                 >
                   <i class="el-icon-plus"></i>
                 </el-upload>
                 <div class="el-upload__tip" slot="tip">支持jpg/png文件，且不超过5MB，必须上传1张图片</div>
              </el-form-item>
           </el-col>
         </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCase, getCase, addCase, updateCase, delCase } from "@/api/official/case"
import { getToken } from "@/utils/auth"
import axios from 'axios'

export default {
  name: "Case",
     dicts: ['yes_or_no', 'case_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 案例表格数据
      caseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        type: undefined
      },
      // 表单参数
      form: {},
                // 表单校验
              rules: {
          title: [
            { required: true, message: "案例标题不能为空", trigger: "blur" }
          ],
          type: [
            { required: true, message: "案例类型不能为空", trigger: "change" }
          ],
          summary: [
            { required: true, message: "案例简介不能为空", trigger: "blur" }
          ],
          description: [
            { required: true, message: "案例描述不能为空", trigger: "blur" }
          ],
          sortNum: [
            { required: true, message: "排序号不能为空", trigger: "blur" }
          ],
                     isShow: [
             { required: true, message: "显示状态不能为空", trigger: "change" }
           ],
                       indicator: [
              {
                required: true,
                validator: (rule, value, callback) => {
                  if (!this.form.indicator || this.form.indicator.length === 0) {
                    callback(new Error('至少需要添加1个指标'));
                  } else {
                    callback();
                  }
                },
                trigger: 'change'
              }
            ],
           imageFileId: [
             {
               required: true,
               validator: (rule, value, callback) => {
                 if (!this.imageFileList || this.imageFileList.length === 0) {
                   callback(new Error('请上传案例图片'));
                 } else {
                   callback();
                 }
               },
               trigger: 'change'
             }
           ]
        },
             // 上传相关
       uploadAction: process.env.VUE_APP_BASE_API + '/system/file/upload',
       uploadHeaders: { Authorization: 'Bearer ' + getToken() },
       imageFileList: [],
       // 富文本编辑器相关
       html: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询案例列表 */
    getList() {
      this.loading = true
      listCase(this.queryParams).then(response => {
        this.caseList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
         // 表单重置
          reset() {
                 this.form = {
           id: undefined,
           title: undefined,
           type: undefined,
           summary: undefined,
           description: undefined,
           sortNum: 0,
           isShow: 1,
           indicator: [],
           imageFileId: null
         }
       this.imageFileList = []
       this.resetForm("form")
     },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加案例"
    },
         /** 修改按钮操作 */
     handleUpdate(row) {
       this.reset()
       const id = row.id || this.ids
       getCase(id).then(response => {
         this.form = response.data
         // 处理图片回显
         if (this.form.imageFileUrl) {
           this.imageFileList = [{
             name: '案例图片',
             url: this.form.imageFileUrl,
             uid: this.form.imageFileId
           }]
         }
         this.open = true
         this.title = "修改案例"
       })
     },
         /** 提交按钮 */
     submitForm() {
       this.$refs["form"].validate(valid => {
         if (valid) {
           // 处理图片文件ID - 只取第一个图片的ID
           this.form.imageFileId = this.imageFileList.length > 0 ? this.imageFileList[0].uid : null

           if (this.form.id != undefined) {
             updateCase(this.form).then(response => {
               this.$modal.msgSuccess("修改成功")
               this.open = false
               this.getList()
             })
           } else {
             addCase(this.form).then(response => {
               this.$modal.msgSuccess("新增成功")
               this.open = false
               this.getList()
             })
           }
         }
       })
     },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除案例编号为"' + ids + '"的数据项？').then(function() {
        return delCase(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
               // 添加指标
      addIndicator() {
        if (!this.form.indicator) {
          this.$set(this.form, 'indicator', [])
        }
        this.form.indicator.push({
          value: '',
          label: ''
        })
        // 触发表单验证
        this.$nextTick(() => {
          this.$refs.form.validateField('indicator')
        })
      },
                       // 删除指标
       removeIndicator(index) {
         if (this.form.indicator.length <= 1) {
           this.$modal.msgError('至少需要保留1个指标');
           return;
         }
         this.form.indicator.splice(index, 1)
         // 触发表单验证
         this.$nextTick(() => {
           this.$refs.form.validateField('indicator')
         })
       },
    // 图片上传前校验
    onBeforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isImage) {
        this.$modal.msgError('只能上传图片文件!')
        return false
      }
      if (!isLt5M) {
        this.$modal.msgError('图片大小不能超过 5MB!')
        return false
      }
      return true
    },
         // 图片上传成功
     onImageUploadSuccess(res) {
       if (res && res.code === 200 && res.data) {
         this.imageFileList.push({
           name: res.data.originalName,
           url: res.data.fullPath,
           uid: res.data.id
         })
         // 触发表单验证
         this.$nextTick(() => {
           this.$refs.form.validateField('imageFileId')
         })
       } else {
         this.$modal.msgError(res && res.msg ? res.msg : '上传失败')
       }
     },
    // 图片上传失败
    onImageUploadError() {
      this.$modal.msgError('上传失败，请重试')
    },
              // 图片移除
      onImageUploadRemove(file) {
        const index = this.imageFileList.findIndex(item => item.uid === file.uid)
        if (index > -1) {
          this.imageFileList.splice(index, 1)
          // 触发表单验证
          this.$nextTick(() => {
            this.$refs.form.validateField('imageFileId')
          })
        }
      },
     // 将图片上传到服务器，返回地址替换到md中
     $imgAdd(pos, $file) {
       const formdata = new FormData()
       formdata.append('file', $file)
       axios({
         url: process.env.VUE_APP_BASE_API + '/system/file/upload',
         method: 'post',
         data: formdata,
         headers: {
           'Content-Type': 'multipart/form-data',
           'Authorization': 'Bearer ' + getToken()
         }
       }).then(res => {
         // 期望结构：{ code, msg, data: { fullPath } }
         const fullPath = res && res.data && res.data.data && res.data.data.fullPath
         if (fullPath) {
           this.$refs.md.$img2Url(pos, fullPath)
         } else {
           this.$modal.msgError('上传成功但未返回文件地址')
         }
       }).catch(err => {
         console.error('img upload error', err)
         this.$modal.msgError('上传图片失败')
       })
     },
     change(value, render) {
       this.html = render
     }
  }
}
</script>

<style scoped>
.metrics-container {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
}

.metrics-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.metrics-title {
  font-weight: bold;
  color: #303133;
}

.metrics-list {
  margin-bottom: 16px;
}

.metric-item {
  background: #fafafa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 12px;
  width: 100%;
}

.metric-item .el-row {
  margin: 0 !important;
}

.metric-item .el-col {
  padding: 0 8px;
}

.metric-item:last-child {
  margin-bottom: 0;
}

.metrics-empty {
  text-align: center;
  padding: 20px;
  color: #909399;
}
</style>
